package com.maple.mapleoj.judge.strategy;

import cn.hutool.json.JSONUtil;
import com.maple.mapleoj.model.dto.question.JudgeCase;
import com.maple.mapleoj.model.dto.question.JudgeConfig;
import com.maple.mapleoj.judge.codesandbox.model.JudgeInfo;
import com.maple.mapleoj.model.entity.Question;
import com.maple.mapleoj.model.enums.JudgeInofoMessageEnum;

import java.util.List;


/**
 * Java程序判题策略
 */
public class JavaLanguageJudgeStrategy implements JudgeStrategy{

    /**
     * 执行判题
     * @param judgeContext
     * @return
     */
    @Override
    public JudgeInfo doJudge(JudgeContext judgeContext) {
        //5)根据沙箱执行结果，设置提交状态和信息
         JudgeInfo judgeInfo = judgeContext.getJudgeInfo();
         List<String> inputList = judgeContext.getInputList();
         List<String> outputList = judgeContext.getOutputList();
         List<JudgeCase> judgeCaseList = judgeContext.getJudgeCaseList();
         Question question = judgeContext.getQuestion();


        Long time = judgeInfo.getTime();
        Long memory = judgeInfo.getMemory();
        String judgeConfigStr = question.getJudgeConfig();;
        JudgeConfig judgeConfig = JSONUtil.toBean(judgeConfigStr,  JudgeConfig.class);
        Long needTimeLimit = judgeConfig.getTimeLimit();
        Long needMemoryLimit = judgeConfig.getMemoryLimit();

        JudgeInfo judgeInfoResponses = new JudgeInfo();
        judgeInfoResponses.setMemory(memory);
        judgeInfoResponses.setTime(time);

        JudgeInofoMessageEnum judgeInofoMessageEnum = JudgeInofoMessageEnum.ACCEPTED;

        if(outputList.size() != inputList.size()){
            judgeInofoMessageEnum = JudgeInofoMessageEnum.WRONG_ANSWER;
            judgeInfoResponses.setMessage(judgeInofoMessageEnum.getValue());
            return  judgeInfoResponses;
        }
        for(int i=0; i < judgeCaseList.size(); i++){
            JudgeCase judgeCase = judgeCaseList.get(i);
            if(!judgeCase.getOutput().equals(outputList.get(i))){
                judgeInofoMessageEnum = JudgeInofoMessageEnum.WRONG_ANSWER;
                judgeInfoResponses.setMessage(judgeInofoMessageEnum.getValue());
                return  judgeInfoResponses;
            }
        }

        //判断题目限制 java程序二倍时限和空间
        if(time > needTimeLimit*2){
            judgeInofoMessageEnum = JudgeInofoMessageEnum.TIME_LIMIT_EXCEEDED;
            judgeInfoResponses.setMessage(judgeInofoMessageEnum.getValue());
            return  judgeInfoResponses;
        }
        if(memory > needMemoryLimit*2){
            judgeInofoMessageEnum = JudgeInofoMessageEnum.MEMORY_LIMIT_EXCEEDED;
            judgeInfoResponses.setMessage(judgeInofoMessageEnum.getValue());
            return  judgeInfoResponses;
        }
        judgeInfoResponses.setMessage(judgeInofoMessageEnum.getValue());
        return  judgeInfoResponses;
    }
}
